package com.cdm.forum.service.impl;

import com.cdm.forum.common.Result;
import com.cdm.forum.common.ResultCode;
import com.cdm.forum.dao.ArticleMapper;
import com.cdm.forum.exception.ApplicationException;
import com.cdm.forum.model.Article;
import com.cdm.forum.model.Board;
import com.cdm.forum.model.User;
import com.cdm.forum.service.IArticleService;
import com.cdm.forum.service.IBoardService;
import com.cdm.forum.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Resource
    private IUserService userService;
    @Resource
    private IBoardService boardService;

    /**
     * 发布帖子
     * @param article 要发部帖子
     */
    @Override
    public void createArticle(Article article) {
        //非空校验
        if(article == null || article.getUserId() == null || article.getBoardId() == null
                || article.getTitle() == null
                || article.getContent() == null
                || StringUtils.isEmpty(article.getTitle())
                || StringUtils.isEmpty(article.getContent())){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }

        //设置默认值
        article.setVisitCount(0);
        article.setLikeCount(0);
        article.setReplyCount(0);
        article.setDeleteState((byte)0);

        //设置时间
        Date now = new Date();
        article.setCreateTime(now);
        article.setUpdateTime(now);

        //写入数据库
        int row = articleMapper.insertSelective(article);
        if(row <= 0){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_CREATE));
        }

        /**
         * 查找用户信息
         */
        User user = userService.selectById(article.getUserId()); // 获取用户信息
        if(user == null){
            log.warn(ResultCode.FAILED_CREATE.toString()+", 发帖失败 id：" + article.getUserId());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_CREATE));
        }

        //更新用户发帖数
        userService.addOneArticleCountById(user.getId());

        /**
         * 查找板块信息
         */
        Board board = boardService.selectByPrimaryKey(article.getBoardId());
        if(board == null) {
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString() + "没有该id:" + article.getBoardId());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }

        //更新板块帖子数量
        boardService.addOneArticleCountById(board.getId());

        log.info(ResultCode.SUCCESS.toString() + "userid:" + user.getId() + ",boardid:" + board.getId()+"articleid:" + article.getId()+"发帖成功");

//        throw new ApplicationException(Result.failed("事务回滚"));
    }

    //获取板块列表
    @Override
    public List<Article> selectAll() {
        //调用Mapper
        List<Article> articles = articleMapper.selectAll();
        return articles;
    }

    //根据板块id获取板块列表
    @Override
    public List<Article> selectBoardById(Long boardId) {
        if(boardId == null || boardId <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //校验板块id是否存在
        Board board = boardService.selectByPrimaryKey(boardId);
        if(board == null) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        //根据板块id获取板块列表
        List<Article> articles = articleMapper.selectBoardById(boardId);

        return articles;
    }
    //根据帖子id获取帖子信息
    @Override
    public Article selectDetailById(Long id) {
        //非空校验
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //调用dao
        Article article = articleMapper.selectDetailById(id);
        if(article == null) {
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        //更新帖子访问次数
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() + 1);

        //保存到数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row <= 0){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(Result.failed(ResultCode.ERROR_SERVICES));
        }

        //返回详细信息,访问数加一
        article.setVisitCount(article.getVisitCount() + 1);

        return article;
    }

    @Override
    public Article selectById(Long id) {
        //非空校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用mapper
        Article article = articleMapper.selectByPrimaryKey(id);

        return article;
    }

    @Override
    public void modifyArticle(Long id, String title, String content) {
        if (id == null || id <= 0
                || StringUtils.isEmpty(title)
                || StringUtils.isEmpty(content) ){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //构建更新对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        updateArticle.setUpdateTime(new Date());

        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(Result.failed(ResultCode.ERROR_SERVICES));
        };
    }

    /**
     *
     * @param id 帖子id
     */
    @Override
    public void thumbsUpById(Long id) {
        //校验
        if (id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //获取帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null || article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        //判断帖子状态
        if( article.getState() == 1) {
            //打印日志
            log.info(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        //构造更新对象
        //构建更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() + 1);
        updateArticle.setUpdateTime(new Date());

        //调用mapper
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(Result.failed(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public void deleteById(Long id) {
        //校验参数
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //根据id查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null || article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        //构造一个新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);

        //调用mapper,更新数据库的帖子状态
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(Result.failed(ResultCode.ERROR_SERVICES));
        }
        //更新板块里面的帖子数
        boardService.subOneArticleCountById(article.getBoardId());
        //更新用户里面的帖子数
        userService.subOneArticleCountById(article.getUserId());

        log.info("删除帖子成功...boardId"+ article.getBoardId()+", userId"+ article.getUserId());
    }

    @Override
    public void addOneArticleReplyCountById(Long id) {
        //校验参数
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //获取帖子信息,看看是否有该帖子
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null || article.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        //判断帖子状态， 静止评论
        if(article.getState() == 1) {
            //打印日志
            log.info(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }


        //构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setUpdateTime(new Date());

        //回复数+1
        updateArticle.setReplyCount(article.getReplyCount() + 1);

        //调用Mapper
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        if(userId == null || userId <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //用户是否存在
        User user = userService.selectById(userId);
        if(user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //调用mapper
        List<Article> articles = articleMapper.selectByUserId(userId);
        return  articles;
    }


}
